from __future__ import annotations
from msgspec import Struct, json
from typing import TypeVar, Self

T = TypeVar('T', bound='MessageStruct')

class MessageStruct(Struct, kw_only=True, omit_defaults=True):
    """
    Base structure for all message types with built-in serialization/deserialization.
    
    All subclasses automatically inherit:
    - kw_only=True: All fields must be specified as keyword arguments
    - omit_defaults=True: Fields with default values are omitted from serialization
    - from_bytes(): Classmethod for deserialization from JSON bytes
    - to_bytes(): Instance method for serialization to JSON bytes
    """
    
    @classmethod
    def from_bytes(cls, data: bytes) -> Self:
        """Deserialize from JSON bytes, returns instance of the calling class"""
        return json.decode(data, type=cls)
    
    def to_bytes(self) -> bytes:
        """Serialize to JSON bytes"""
        return json.encode(self)